<?php
$response = array();

if (isset($_GET['userid'])) {
	$userid = $_GET['userid'];
}

mysql_connect("localhost", "web964", "pass17") or die("Connection failed.");
mysql_select_db("usr_web964_1") or die("Database does not exist.");

$erg = mysql_query("SELECT
						id,						
						name,
						description,
						measurename,
						priority,
						startvalue,
						value,
						targetvalue,
						fk_measuretypeid						
						FROM goal WHERE goal.fk_userid=" . $userid) or die("MySQL-Error 1: " . mysql_error());

if (mysql_num_rows($erg) == 0) {#count(id) AS dbgoalscounter
	$response["numberOfGoals"] = "0";
} else {
	$response['numberOfGoals'] = mysql_num_rows($erg);
	$goalcounter = 1;
	while ($row = mysql_fetch_object($erg)) {# goal loop

		$goalArray = array();
		$goalid = $row -> id;
		$goalArray['goalname_' . $goalcounter] = $row -> name;
		$goalArray['description_' . $goalcounter] = $row -> description;
		$goalArray['measurename_' . $goalcounter] = $row -> measurename;
		$goalArray['measuretype_' . $goalcounter] = $row -> measuretype;
		$goalArray['start_' . $goalcounter] = $row -> startvalue;
		$goalArray['current_' . $goalcounter] = $row -> value;
		$goalArray['target_' . $goalcounter] = $row -> targetvalue;
		$measuretypeid = $row -> fk_measuretypeid;

		switch ($row->priority) {
			case "ui" :
				$goalArray['priority_' . $goalcounter] = "urgent / important";
				break;
			case "uni" :
				$goalArray['priority_' . $goalcounter] = "urgent / unimportant";
				break;
			case "nui" :
				$goalArray['priority_' . $goalcounter] = "unurgent / important";
				break;
			case "nuni" :
				$goalArray['priority_' . $goalcounter] = "unurgent / unimportant";
				break;
		}
		$goalHasSubgoals = true;
		$result_subgoalsnumber = mysql_query("SELECT * FROM subgoal WHERE fk_goalid='$goalid'") or die("MySQL-Error 2: " . mysql_error());
		if (mysql_num_rows($result_subgoalsnumber) == 0) {
			$goalArray['subgoalscounter_' . $goalcounter] = "(0 subgoals)";
			$goalHasSubgoals = false;
		} else if (mysql_num_rows($result_subgoalsnumber) == 1) {
			$goalArray['subgoalscounter_' . $goalcounter] = "(1 subgoal)";
		} else {
			$goalArray['subgoalscounter_' . $goalcounter] = "(" . mysql_num_rows($result_subgoalsnumber) . " subgoals)";
		}
		
		if($goalHasSubgoals){			
			$goalArray['current_' . $goalcounter] = calculateCurrentValueIfSubgoalsExist($goalid);
		}
		
		$deadlineSet = false;
		$result_deadline = mysql_query("SELECT date FROM goaldeadline WHERE fk_goalid='$goalid'") or die("MySQL-Error 3: " . mysql_error());
		while ($row3 = mysql_fetch_object($result_deadline)) {
			if (mysql_num_rows($result_deadline) == 1) {
				$goalArray['goaldeadline_' . $goalcounter] = "$row3->date";
				$deadlineSet = true;
			} else if (mysql_num_rows($result_deadline) == 0) {
				$goalArray['goaldeadline_' . $goalcounter] = "-";
				$deadlineSet = true;
			}
		}
		if (!$deadlineSet) {
			$goalArray['goaldeadline_' . $goalcounter] = "-";
		}

		$result_measuretype = mysql_query("SELECT typename FROM measuretype WHERE id='$measuretypeid'") or die("MySQL-Error 4: " . mysql_error());
		while ($row4 = mysql_fetch_object($result_measuretype)) {
			$goalArray['measuretype_' . $goalcounter] = $row4 -> typename;
		}

		$response[$goalcounter] = $goalArray;
		$goalcounter++;

	} # end of goal loop

	####################################################### Anfang
	/*

	 if ($hasSubgoals == true){
	 $result_subgoals = mysql_query(
	 "SELECT subgoal.id AS subgoalid, startvalue, targetvalue, value, measuretype.typename
	 FROM subgoal, measuretype
	 WHERE subgoal.fk_goalid='$goalid' AND measuretype.id=subgoal.fk_measuretypeid")
	 or die ("MySQL-Error: " . mysql_error());

	 $subgoalsPercentageArray = array();
	 while($row5 = mysql_fetch_object($result_subgoals)){
	 $startV = $row5->startvalue;
	 $targetV = $row5->targetvalue;
	 $currentV = $row5->value;
	 $subgoalmeasureType = $row5->typename;

	 #echo "computed : ".computePercentage(floatval($startV), floatval($currentV), floatval($targetV), $subgoalmeasureType);
	 if ($subgoalmeasureType == "yes/no"){
	 $subgoalsPercentageArray[] = computePercentage($startV, $currentV, $targetV, $subgoalmeasureType);
	 }else{
	 $subgoalsPercentageArray[] = computePercentage(floatval($startV), floatval($currentV), floatval($targetV), $subgoalmeasureType);
	 }
	 }

	 $totalPercentageOfGoal = computeTotalPercentageOfGoal($subgoalsPercentageArray);
	 $canvasid = "canvas_".$goalid."_0"."_100"."_$totalPercentageOfGoal";

	 #test
	 #foreach ($subgoalsPercentageArray as $i  => $value) {
	 #echo "array: $subgoalsPercentageArray[$i]<br/>";
	 #}
	 #end of test

	 echo "<td><canvas id=\"$canvasid\" width=\"100\" height=\"10\"></canvas></td>";
	 echo "<td></td>";

	 echo "<td>0</td>";
	 echo "<td>".round($totalPercentageOfGoal, 2)."</td>";
	 echo "<td>100</td>";

	 }else{
	 $canvasid = "canvas_".$goalid."_$row->startvalue"."_$row->targetvalue"."_$row->value";
	 echo "<td><canvas id=\"$canvasid\" width=\"100\" height=\"10\"></canvas></td>";
	 echo "<td></td>";
	 echo "<td>$row->startvalue</td>";
	 echo "<td>$row->value</td>";
	 echo "<td>$row->targetvalue</td>";
	 }

	 $subgoalpriority = "";
	 switch ($row->priority) {
	 case "ui":
	 $subgoalpriority = "urgent / important";
	 break;
	 case "uni":
	 $subgoalpriority = "urgent / unimportant";
	 break;
	 case "nui":
	 $subgoalpriority = "unurgent / important";
	 break;
	 case "nuni":
	 $subgoalpriority = "unurgent / unimportant";
	 break;
	 }
	 echo "<td>$subgoalpriority</td>";
	 echo "<td><a href=\"index.php?page=edit&goalid=$goalid\" ><img width=\"35.5px\" src=\"lib/img/buttonEdit.png\"/></a></td>";
	 echo "<td><a href=\"index.php?page=overview&del=$goalid\"><img width=\"50px\" src=\"lib/img/buttonDelete.png\"/></a></td>";
	 echo "</tr>";
	 }*/

	####################################################### Ende

}

echo json_encode($response);

function getUserId($email, $password) {
	$result = mysql_query("SELECT id FROM users WHERE email='$email' AND password='$password'");
	if (mysql_num_rows($result) == 0) {
		return -1;
	}
	while ($row = mysql_fetch_object($result)) {
		$userid = $row -> id;
	}
	return $userid;
}

	function calculateCurrentValueIfSubgoalsExist($goalid){ 
		mysql_connect("localhost", "web964","pass17") or die ("Connection failed.");
		mysql_select_db("usr_web964_1") or die ("Database does not exist.");
	
		$result = mysql_query("SELECT * FROM subgoal WHERE fk_goalid =".$goalid)or die ("MySQL-Fehler: " . mysql_error());
		$sumPersentage = 0;
		while($row = mysql_fetch_object($result)){
			
				$sumPersentage += computePercentage($row->startvalue, $row->targetvalue, $row->value);
			
		}		
		return number_format($sumPersentage / mysql_num_rows($result), 2);
	}
	
	function computePercentage($start, $target, $current){
		if($start == "no" && $target == "yes"){
			if ($current == "yes"){
				return 100;
			}
			return 0;
		}
		
		if ($target == $start){
			return 100;
		}
		return abs($current - $start) * 100 / abs($target - $start);
	}
?>